#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>

// int open(const char *pathname, int flags);
// int open(const char *pathname, int flags, mode_t mode);
// ssize_t write(int fd, const void *buf, size_t count);
// ssize_t read(int fd, void *buf, size_t count);
// off_t lseek(int fd, off_t offset, int whence);
#define SAMPLE_STR "hello,wzq."
#define BUF_LEN (sizeof(SAMPLE_STR))
#define FILE_NAME "foo.txt"

void main(void) {
	int fd;
	// S_IRUSR  Permits the file's owner to read it.
	mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

	fd = open(FILE_NAME,
	          O_RDWR | O_CREAT | O_TRUNC,
	          mode);

	// write to it
	write(fd, SAMPLE_STR, BUF_LEN);

	// read it
	lseek(fd, 0, SEEK_SET); // set to 0
	char buf[BUF_LEN + 100];
	int read_cnt = read(fd, buf, BUF_LEN + 100);
	printf("read_cnt=%d\n", read_cnt);
	buf[read_cnt] = '\0';
	puts(buf);
	close(fd);
}